package com.yj.consumer;

import com.yj.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RpcConsumer implements InitializingBean, DisposableBean {

    EventLoopGroup eventLoopGroup;

    @Value("${server.host:127.0.0.1}")
    private String host;

    //@Value("${server.port:9001}")
    private int port = 9001;

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(()->{
            try {
                eventLoopGroup = new NioEventLoopGroup();
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(eventLoopGroup)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new StringEncoder());
                                ch.pipeline().addLast(new StringDecoder());
                                ch.pipeline().addLast(new RpcClientHandler());
                            }
                        });
                log.info("客户端启动成功！");
                ChannelFuture future = bootstrap.connect(host, port).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                log.error("客户端启动失败！[{}]", e.getMessage());
            }
        }).start();
    }

    @Override
    public void destroy() {
        eventLoopGroup.shutdownGracefully();
    }

}
